import React, { Component } from 'react';
import { NavBar } from 'antd-mobile';
import './index.scss'
import axios from 'axios';
import { getCurrentCity } from '../../utils';

// 格式化城市的数据格式
const formatCityDate = (list) => {
  const cityList = {}
  list.forEach(item => {
    const first = item.short.substr(0, 1) // 截取字符串
    // 如果已经有有数据了，就直接 push 进入数组
    if (cityList[first]) {
      cityList[first].push(item)
    // 第一次填写进数组
    }else {
      cityList[first] = [item]
    }
  })
  // Object.keys(cityList) 会返回一个数组，在进行升序的排序
  const cityIndex = Object.keys(cityList).sort()
  return {
    cityList,
    cityIndex
  }
}

class CityList extends Component {
//  获取
  async getCityList() {
    const res = await axios.get(`http://localhost:8080/area/city?level=1`)
    const { cityList, cityIndex } = formatCityDate(res.data.body)
   
    
    const hotRes = await axios.get(`http://localhost:8080/area/hot`)
    cityList['hot'] = hotRes.data.body
    cityIndex.unshift('hot') 

    const curCity = await getCurrentCity()
    // 添加新的下标
    cityList['#'] = [curCity]
    cityIndex.unshift('#')
    console.log(cityList, cityIndex);
    
  }
  componentDidMount() {
    this.getCityList()
  }
  render() {
    return (
      <div className="cityList">
        <NavBar
          className="navBar"
          mode="light"
          icon={<i className="iconfont icon-back" />}
          onLeftClick={() => this.props.history.push('/home')}
        >城市选择</NavBar>
      </div>
    );
  }
}

export default CityList;